<template>
	<view class="box">
		<!-- 弹出层 -->
		<uni-popup ref="popup" background-color="#fff" @change="changePopup">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<view class="top">
					<view class="dateCard" v-if="!isPackage">
						<!-- 日期弹窗 -->
						<view class="date">
							<uni-datetime-picker type="date" @change="dateChange">{{date}}
								{{time}}</uni-datetime-picker>
						</view>
						<view class="icon">

						</view>
					</view>
					<view class="content">
						<!-- 食物信息 -->
						<ppc-food-card @click="foodClick" :dataSource="foodData"></ppc-food-card>
					</view>
				</view>
				<view class="center">
					<!-- 食物总热量 -->
					<view class="caloric">
						<view class="text">
							<text class="number">{{caloric}}</text>
							<text class="unit">千卡</text>
						</view>
						<view class="line">
						</view>
					</view>
					<!-- 食物营养元素比例图 -->
					<view class="charts-box">
						<canvas style="width: 100%; height: 100%;" type="2d" id="homeownerCanvas"
							class="homeowner-canvas_charts"></canvas>
					</view>
					<!-- 食物详情营养元素比例数值 -->
					<view class="tips">
						<view class="component" v-for="(item,index) in nutritionData" :key="index">
							<view :class="'icon'+index">

							</view>
							<text class="name">{{item.title}}</text>
							<text class="value">{{item.value}}</text>
							<text class="unit">克</text>
						</view>
					</view>
				</view>
				<view class="bottom">
					<!-- 滑动计量条 -->
					<view class="">
						<text class="value">{{metering}}</text>
						<text class="unit">{{unitValue}}</text>
					</view>
					<ppc-sapling-scale :min="0" :max="2400" :int="true" :single="10" :h="50" :active="startValue"
						:styles="styles" @value="changeValue" />
					<view class="unitBox">
						<view class="item" v-for="(item,index) in units" :key="index" @click="unitClick(item.text)">
							<image class="image"
								:src="unitValue==item.text?'../static/icon/'+item.eng+'_active.png':'../static/icon/'+item.eng+'.png'"
								mode="aspectFit"></image>
							<text :class="unitValue==item.text? 'active unitText':'unitText'">{{item.text}}</text>
						</view>
					</view>
				</view>
				<!-- 底部按钮 -->
				<view class="bottomBtn">
					<view class="cancel" @click="cancelClick">
						<text>取消</text>
					</view>
					<view class="save" @click="saveClick">
						<text>确定</text>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		getCurrentInstance,
		nextTick,
		onMounted,
		ref,
		toRef,
		watch
	} from 'vue';
	import canvas from '/tools/canvas.js'
	import {
		onReady
	} from '@dcloudio/uni-app'
	import ppcSaplingScale from '@/components/ppcSaplingScale.vue';
	import ppcFoodCard from '/components/ppcFoodCard.vue'
	const props = defineProps({
		type: {
			type: Number,
			default: 1 //1为新增2为修改
		},
		date: {
			type: String,
			default: () => {
				let date = new Date();
				const seperator1 = "月";
				const seperator2 = "日"
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let strDate = date.getDate();
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (strDate >= 0 && strDate <= 9) {
					strDate = "0" + strDate;
				}
				let currentdate = month + seperator1 + strDate + seperator2
				return currentdate;
			} //日期
		},
		time: {
			type: String,
			default: "" //早中晚餐
		},
		foodData: {
			type: Array,
			default: []
		},
		isShow: {
			type: Boolean,
			default: false
		},
		isPackage: {
			type: Boolean,
			default: false
		}
	})
	//碳水蛋白质以及脂肪比例
	const nutritionData = ref([{
		title: "碳水",
		value: 2
	}, {
		title: "蛋白质",
		value: 3
	}, {
		title: "脂肪",
		value: 4
	}])
	const emits = defineEmits(['notShow'])
	//是否显示组件
	const isShow = ref(props.isShow)
	//父级传的食物信息
	const foodData = ref(props.foodData)
	//父级传的日期
	const date = ref(props.date)
	//父级传的时间
	const time = ref(props.time.slice(2, 4))
	//父级传的食物初始计量
	const startValue = ref(props.foodData[0].number)
	//父级传的食物初始热量
	const caloric = ref(props.foodData[0].caloric)
	//是否显示饼状图(popup默认不显示必须加一个判断条件控制饼状图的显隐)
	const reshowChart = ref(0)
	//饼状图的食物信息
	const canvasData = ref([{
			"value": 0.5,
			"color": "#FC8452",
			"title": "碳水"
		},
		{
			"value": 0.3,
			"color": "#91CB74",
			"title": "蛋白质"
		},
		{
			"value": 0.2,
			"color": "#FAC858",
			"title": "脂肪"
		}
	])
	//选择的计量单位的索引
	const current = ref(0)
	//计量的数值
	const metering = ref(0)
	//碳水的含量
	const carbohydrate = ref()
	//蛋白质的含量
	const protein = ref()
	//脂肪的含量
	const fat = ref()
	const popup = ref()
	const units = ref([{
		icon: '../static/icon/gram_active',
		text: '克',
		eng: 'gram'
	}])
	const unitValue = ref('克')
	const eopts = ref({
		title: {
			name: "",
			fontSize: 15,
			color: "#666666"
		},
		subtitle: {
			name: "",
			fontSize: 25,
			color: "#7cb5ec"
		},
	})
	const placeholderStyle = "color:#87C38F;font-size:14px";
	const styles = {
		line: '#dbdbdb',
		bginner: '#fbfbfb',
		bgoutside: '#ffffff',
		font: '#404040',
		fontColor: '#404040',
		fontSize: 16,
	};
	// 监听父级是否点击了popup弹窗
	watch(isShow, (newValue, oldValue) => {
		if (!newValue) {
			emits("notShow", 'notShow')
		}
	})
	onReady(() => {
		carbohydrate.value = foodData.value[0].carbohydrate /
			foodData.value[0].number
		protein.value = foodData.value[0].protein /
			foodData.value[0].number
		fat.value = foodData.value[0].fat /
			foodData.value[0].number
		const sum = carbohydrate.value + protein.value + fat.value
		canvasData.value.forEach(item => {
			if (item.title == '碳水') {
				item.value = carbohydrate.value / sum
			}
			if (item.title == '蛋白质') {
				item.value = protein.value / sum
			}
			if (item.title == '脂肪') {
				item.value = fat.value / sum
			}
		})
		calculateCaloric(props.foodData[0].number)
		if (isShow.value) {
			popup.value.open("bottom")
			const instance = getCurrentInstance()
			nextTick(() => {
				let query = uni.createSelectorQuery().in(instance).select(`#homeownerCanvas`).fields({
					node: true,
					size: true
				}).exec(res => {
					const width = res[0].width
					const height = res[0].height
					canvas.canvasGraph('homeownerCanvas', canvasData.value, -1, instance, (height -
							10) / 2,
						(height / 2) - 2)
				})

			})
		}
		// 如果食物有其他计量单位就补充到计量单位数组中
		if (foodData.value[0].unit != '克') {
			units.value.push({
				text: foodData.value[0].unit,
				icon: '../static/icon/metering.png',
				eng: 'metering'
			})
			unitValue.value = foodData.value[0].unit
		}
	})
	// 食物信息点击查看食物详情信息
	const foodClick = () => {

	}
	// 切换计量单位
	const unitClick = (e) => {
		if (e !== unitValue.value) {
			unitValue.value = e
		}
	}
	// popup弹窗的显隐状态触发事件
	const changePopup = (e) => {
		if (e.show) {

		} else {
			isShow.value = false
		}
	}
	// 滑动计量条数值改变触发事件
	const changeValue = (e) => {
		metering.value = e
		calculateCaloric(e)
	}
	// popup底部取消事件
	const cancelClick = () => {
		popup.value.close()
	}
	// popup底部确定事件
	const saveClick = () => {
		let data
		if (!props.isPackage) {
			data = {
				foodId: props.foodData[0]._id,
				unit: foodData.value[0].unit,
				metering: metering.value,
				date: date.value,
				caloric: Number(caloric.value)
			}
		} else {
			data = {
				foodData: props.foodData[0],
				caloric: Number(caloric.value)
			}
			data.foodData.metering = metering.value
			data.foodData.totalCaloric = Number(caloric.value)
		}
		emits("foodData", data)
		popup.value.close()
	}
	//实时计算热量
	const calculateCaloric = (e) => {
		//计算热量
		caloric.value = Number(((props.foodData[0].caloric / props.foodData[0].number) * e).toFixed(0));
		nutritionData.value.forEach(item => {
			if (item.title == '碳水') {
				item.value = (carbohydrate.value * e).toFixed(1)
			}
			if (item.title == '蛋白质') {
				item.value = (protein.value * e).toFixed(1)
			}
			if (item.title == '脂肪') {
				item.value = (fat.value * e).toFixed(1)
			}
		})
	}
	//日期选择
	const dateChange = (e) => {
		let a = e.slice(e.indexOf('-') + 1, e.length)
		let b = a.split('-')
		date.value = b.join('月') + '日'
	}
</script>

<style lang="scss">
	.popup-content {
		height: 850rpx;
		display: flex;
		flex-direction: column;
		margin: 20rpx 0;

		.top {
			height: 25%;

			.dateCard {
				margin-bottom: 2%;
				padding-bottom: 2%;
				display: flex;
				align-items: center;
				justify-content: center;
				border-bottom: 1px solid #f1f1f1;

				.date {
					font-size: 32rpx;
					font-weight: bold;
					color: #000;
				}

				.icon {
					position: fixed;
					top: 20rpx;
					right: 20rpx;

				}
			}

			.content {
				margin: 0 20rpx;
			}
		}


		.center {
			height: 20%;
			display: flex;
			justify-content: space-between;
			margin: 0 20rpx;
			align-items: center;

			.caloric {
				height: 100%;
				width: 25%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				color: #afafaf;

				.text {
					margin-left: 30rpx;

					.number {
						font-size: 38rpx !important;
						font-weight: bold;
					}

					.unit {
						font-size: 24rpx !important;

					}
				}


				.line {
					width: 3rpx;
					height: 100%;
					background-color: #dcdcdc;
				}

			}

			.charts-box {
				position: relative;
				z-index: 999;
				width: 45%;
				height: 100%;
			}

			.tips {
				width: 30%;

				.component {
					display: flex;
					align-items: center;

					.icon0 {
						width: 20rpx;
						height: 20rpx;
						margin-right: 8rpx;
						background-color: #FC8452;
					}

					.icon1 {
						width: 20rpx;
						height: 20rpx;
						margin-right: 8rpx;
						background-color: #91CB74;
					}

					.icon2 {
						width: 20rpx;
						height: 20rpx;
						margin-right: 8rpx;
						background-color: #FAC858;
					}

					.name {
						font-size: 24rpx;
						color: #afafaf;
					}

					.value {
						font-size: 28rpx;
						color: #afafaf;
						margin: 0 5rpx;
					}

					.unit {
						font-size: 24rpx;
						color: #afafaf;
					}
				}

			}
		}

		.bottom {
			height: 47%;
			width: 100%;
			display: flex;
			flex-direction: column;
			margin: 0 auto;
			color: #87C38F;
			text-align: center;

			.value {
				font-size: 38rpx;
			}

			.unit {
				font-size: 24rpx !important;

			}

			.unitBox {
				display: flex;
				align-items: center;
				justify-content: space-evenly;
				margin-top: 2%;

				.item {
					display: flex;
					flex-direction: column;
					font-size: 28rpx;

					.image {
						width: 40rpx;
						height: 40rpx;
					}

					.unitText {
						color: #afafaf;
					}

					.active {
						color: #87C38F;
					}
				}
			}

		}

		.bottomBtn {
			display: flex;
			height: 8%;
			align-items: center;
			justify-content: space-between;
			font-size: 32rpx;
			font-weight: bold;

			.cancel {
				border-top: 2rpx solid #87C38F;
				border-bottom: 2rpx solid #87C38F;
				color: #87C38F;
				padding: 18rpx 0;
				width: 50%;
				text-align: center;
			}

			.save {
				width: 50%;
				text-align: center;
				color: #f1f1f1;
				padding: 20rpx 0;
				background-color: #87C38F;
			}
		}
	}
</style>